package zdlog

import (
	"strings"

	log "github.com/cihub/seelog"
	"github.com/fsnotify/fsnotify"
)

func WrapSeeLog(logConfigFilePath string) (log.LoggerInterface, error) {
	logger, err := log.LoggerFromConfigAsFile(logConfigFilePath)

	if err != nil {
		return nil, err
	}
	log.ReplaceLogger(logger)
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Error(err)
	}
	go func() {
		for {
			select {
			case event, ok := <-watcher.Events:
				if !ok {
					return
				}
				if event.Op&fsnotify.Write == fsnotify.Write {
					newLogger, err := log.LoggerFromConfigAsFile(logConfigFilePath)
					if err == nil {
						log.Info("成功加载日志配置变动")
						log.ReplaceLogger(newLogger)
					} else {
						if strings.Index(err.Error(), "content") < 0 {
							log.Info("日志配置变动失败,使用原配置! err=", err)
						}
					}
				}
			case _, ok := <-watcher.Errors:
				if !ok {
					return
				}
			}
		}
	}()

	err = watcher.Add(logConfigFilePath)
	if err != nil {
		log.Error("监控日志配置文件变动失败")
	}
	return logger, nil
}

func InitLogger(youLogger *log.LoggerInterface, logConfigFilePath string) error {
	logger, err := log.LoggerFromConfigAsFile(logConfigFilePath)
	if err != nil {
		return err
	}
	*youLogger = logger
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		return err
	}
	go func() {
		for {
			select {
			case event, ok := <-watcher.Events:
				if !ok {
					return
				}
				if event.Op&fsnotify.Write == fsnotify.Write {
					newLogger, err := log.LoggerFromConfigAsFile(logConfigFilePath)
					if err == nil {
						logger.Info("成功加载日志配置变动")
						if !logger.Closed() {
							logger.Flush()
							logger.Close()
						}
						*youLogger = newLogger
					} else {
						if strings.Index(err.Error(), "content") < 0 {
							logger.Info("日志配置变动失败,使用原配置! err=", err)
						}
					}
				}
			case _, ok := <-watcher.Errors:
				if !ok {
					return
				}
			}
		}
	}()

	err = watcher.Add(logConfigFilePath)
	if err != nil {
		logger.Error("监控日志配置文件变动失败")
	}
	return nil
}
